//
//  SHComposeView.swift
//  SHWeibo01
//
//  Created by 卫平玉 on 16/7/28.
//  Copyright © 2016年 卫平玉. All rights reserved.
//

import UIKit
import pop
class SHComposeView: UIView {
    
     // 代表记录mainVc
    var target: UIViewController?
    //保存compose数组
    lazy var composeButtonInfos: [SHComposeButtonInfo] = [SHComposeButtonInfo]()
    
    lazy var buttons: [SHComposeButton] = [SHComposeButton]()

    override init(frame: CGRect) {
        super.init(frame: CGRectMake(0, 0, SCREENW, SCREENH))
        
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func composeViewShow(target: UIViewController){
        
        self.target = target
        target.view.addSubview(self)
        
        setupButtonsAnim(true)
    }
    
    func setupUI(){
        
        backgroundColor = RandomColor()
        //01添加控件
        addSubview(bgImageView)
        addSubview(logoImageView)
        addChildButtons()
        //02添加约束
        
        bgImageView.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(self).offset(UIEdgeInsetsZero)
        }
        
        logoImageView.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(self).offset(100)
            make.centerX.equalTo(self)
        }
    }
    
    
    //添加按钮
    func addChildButtons(){
        
        composeButtonInfos = getComposeButtonInfos()
        
        let childW: CGFloat = 80
        let childH: CGFloat = 110
        let childMargin: CGFloat = (SCREENW-3*childW)/4
        
        for (i,value) in composeButtonInfos.enumerate(){
            
            let col = CGFloat(i%3)
            let row = CGFloat(i/3)
            
            let button = SHComposeButton()
            
            button.composeButtonInfo = value
            button.addTarget(self, action: "buttonClick:", forControlEvents: UIControlEvents.TouchUpInside)
            
            button.setImage(UIImage(named: value.icon ?? ""), forState: UIControlState.Normal)
            button.setTitle(value.title, forState: UIControlState.Normal)
            
            button.frame = CGRectMake(childMargin+(childMargin+childW)*col, (childH+childMargin)*row+SCREENH, childW, childH)
            
            addSubview(button)
            
            buttons.append(button)
        }
    }
    
    func buttonClick(button: SHComposeButton){
        
        UIView.animateWithDuration(0.25, animations: { () -> Void in
            for value in self.buttons {
                
                self.alpha = 0.2
                
                if button == value{
                    
                   value.transform = CGAffineTransformMakeScale(2, 2)
                }else{
                    
                    value.transform = CGAffineTransformMakeScale(0.2, 0.2)
                }
            }
            
            }) { (_) -> Void in
                
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    for value in self.buttons{
                        
                        self.alpha = 1
                        
                        value.transform = CGAffineTransformIdentity
                    }
                    
                    }, completion: { (_) -> Void in
                        
                        guard let vcName = button.composeButtonInfo?.nextvc else{
                            return
                        }
                        
                        guard let pn = NSBundle.mainBundle().infoDictionary!["CFBundleExecutable"] as? String else{
                            
                            return
                        }
                        
                        guard let cn = NSClassFromString("\(pn).\(vcName)") as? UIViewController.Type else{
                            return
                        }
                        
                        let tempVc = cn.init()
                        
                        let nav = UINavigationController(rootViewController: tempVc)
                        self.target?.presentViewController(nav, animated: true, completion: { () -> Void in
                            self.removeFromSuperview()
                        })
                })
        }
    }
    
     // 读取plist文件 得到数据
    func getComposeButtonInfos() -> [SHComposeButtonInfo]{
        
        let file = NSBundle.mainBundle().pathForResource("compose.plist", ofType: nil)!
        let tempArr = NSArray(contentsOfFile: file)!
        var mutable: [SHComposeButtonInfo] = [SHComposeButtonInfo]()
        for dic in tempArr {
            
          let composeButtonInfo = SHComposeButtonInfo(dict: dic as! [String : AnyObject])
            
            mutable.append(composeButtonInfo)
        }
        
        return mutable
        
    }
    
    //点击屏幕View消失
    
    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
        
         self.setupButtonsAnim(false)
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(0.4 * Double(NSEC_PER_SEC))),dispatch_get_main_queue()) { () -> Void in
            
           self.removeFromSuperview()
        }
    }
    
    //添加动画效果
    
    func setupButtonsAnim(isUp: Bool){
        
        let margin: CGFloat = isUp ? -350 : 350
        
        let set = isUp ? buttons.enumerate() : buttons.reverse().enumerate()
        
        // 遍历按钮数组 分别设置动画
        for (i,value) in set {
            // 设置动画
            let anim = POPSpringAnimation(propertyNamed: kPOPViewCenter)
            // 设置tovalue
            anim.toValue = NSValue(CGPoint: CGPoint(x: value.center.x, y: value.center.y + margin))
            // 开始时间
            anim.beginTime = CACurrentMediaTime() + Double(i)*0.025
            // 弹性系数
            anim.springBounciness = 10
            // 动画速度
            anim.springSpeed = 8
            value.pop_addAnimation(anim, forKey: nil)
        }
        
    }
  
    // 背景磨砂图片
    private lazy var bgImageView: UIImageView = UIImageView(image: UIImage.getScreenShot().applyLightEffect())
    private lazy var logoImageView: UIImageView = UIImageView(imgName: "compose_slogan")

}
